package com.yanze.controller;

import com.yanze.pojo.Bookcommit;
import com.yanze.pojo.Bookimage;
import com.yanze.pojo.Booksecond;
import com.yanze.pojo.User;
import com.yanze.pojo.request.ReqBookCommit;
import com.yanze.pojo.request.SecondBook;
import com.yanze.pojo.response.SecondBookBean;
import com.yanze.service.BookSecondService;
import com.yanze.service.UserService;
import com.yanze.utils.BaseJSONResult;
import com.yanze.utils.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    BookSecondService mBookSercondService;

    @Autowired
    UserService mUserService;

    /**
     * 发布二手书售卖
     */
    @RequestMapping(path = "/publishBook", method = RequestMethod.POST)
    public BaseJSONResult publishBook(@RequestBody SecondBook secondBook) {
        if (secondBook == null) {
            return BaseJSONResult.errorMsg("参数错误");
        }
        Calendar calendar = Calendar.getInstance();
        Long bookid = calendar.getTime().getTime();

        Booksecond book = new Booksecond();
        book.setBookid(bookid);
        book.setBookname(secondBook.getBookname());
        book.setBookdescribe(secondBook.getBookdescribe());
        book.setPrice(secondBook.getPrice());
        book.setPlace(secondBook.getPlace());
        book.setContact(secondBook.getContact());
        book.setUserid(secondBook.getUserid());
        book.setTime(new Date());

        int flag = mBookSercondService.addSecondBook(book);//添加动态

        List<String> images = secondBook.getImages();
        if (images.size() == 1) {
            Bookimage one = new Bookimage();
            one.setBookid(bookid);
            one.setTime(new Date());
            one.setPath(images.get(0));
            mBookSercondService.insertImage(one);
        } else {
            List<Bookimage> friendimages = new ArrayList<>();
            for (int i = 0; i < images.size(); i++) {
                Bookimage image = new Bookimage();
                image.setBookid(bookid);
                image.setTime(new Date());
                image.setPath(images.get(i));
                friendimages.add(image);
            }
            mBookSercondService.insertImages(friendimages);
        }
        if (flag > 0) {
            return BaseJSONResult.ok();
        } else {
            return BaseJSONResult.errorMsg("插入数为0，请检查参数是否有误");
        }
    }

    /**
     * 获取所有二手书信息
     */
    @RequestMapping(path = "/getAllBook/{page}/{pageSize}", method = RequestMethod.GET)
    public BaseJSONResult getAllBook(@PathVariable int page, @PathVariable int pageSize) {
        if (pageSize < 1) {
            pageSize = 1;
        }
        if (page < 1) {
            page = 1;
        }
        List<Booksecond> books = mBookSercondService.getAllSecondBook(page, pageSize);//获取朋友圈动态
        if (books == null || books.isEmpty()) {
            return BaseJSONResult.ok(books);
        }
        List<SecondBookBean> respBooks = getImageByObject(books);
        return BaseJSONResult.ok(respBooks);
    }

    /**
     * 获取个人所有二手书
     */
    @RequestMapping(path = "/getBookById/{userid}/{page}/{pageSize}", method = RequestMethod.GET)
    public BaseJSONResult getBookById(@PathVariable("userid") String userid,
                                      @PathVariable("page") int page,
                                      @PathVariable("pageSize") int pageSize) {
        if (pageSize < 1) {
            pageSize = 1;
        }
        if (page < 1) {
            page = 1;
        }
        List<Booksecond> books = mBookSercondService.getSecondBookById(userid, page, pageSize);
        if (books == null || books.isEmpty()) {
            return BaseJSONResult.ok(books);
        }

        List<SecondBookBean> respBooks = getImageByObject(books);
        return BaseJSONResult.ok(respBooks);
    }

    /**
     * 删除二手书信息
     */
    @RequestMapping(path = "/deleteBook", method = RequestMethod.POST)
    public BaseJSONResult deleteBook(@RequestParam Long bookid) {
        int flag = mBookSercondService.deleteSecondBook(bookid);// java中的int类型最大值是2147483647 存储长度为32bit.所以范围是“-2^32”到“2^32-1”; 也就是“-2147483648”到“2147483647”;
        if (flag > 0) {
            return BaseJSONResult.ok();
        } else {
            return BaseJSONResult.errorMsg("删除数为0，请检查参数是否有误");
        }
    }

    private List<SecondBookBean> getImageByObject(List<Booksecond> books) {
        List<SecondBookBean> respBooks = new ArrayList<>();
        for (int i = 0; i < books.size(); i++) {
            User user = mUserService.queryUserById(books.get(i).getUserid());
            String header;
            String nickname;
            if (user != null) {
                header = user.getUsericon();
                nickname = user.getNickname();
            } else {
                header = "Header/0454f443-b9f6-4d8f-bf41-7e7634265ece.jpg";
                nickname = "匿名用户";
            }

            List<Bookimage> bookimages = mBookSercondService.queryImageByUid(books.get(i).getBookid());//获取动态对应的图片
            List<String> images = new ArrayList<>();
            for (int j = 0; j < bookimages.size(); j++) {
                images.add(bookimages.get(j).getPath());
            }
            SecondBookBean tempBean = new SecondBookBean(books.get(i), images, header, nickname);
            respBooks.add(tempBean);
        }
        return respBooks;
    }


    /**
     * 添加二手书评论
     */
    @RequestMapping(path = "/publisBookCommit", method = RequestMethod.POST)
    public BaseJSONResult publisBookCommit(@RequestBody ReqBookCommit commit) {
        if (commit == null) {
            return BaseJSONResult.errorMsg("参数错误");
        }
        Calendar calendar = Calendar.getInstance();
        Long commitid = calendar.getTime().getTime();

        Bookcommit bookcommit = new Bookcommit();
        bookcommit.setCommitid(commitid);
        bookcommit.setTime(new Date());
        bookcommit.setBookid(commit.getBooksecondid());
        bookcommit.setUserid(commit.getUserid());
        bookcommit.setContent(commit.getContent());
        int flag = mBookSercondService.addBookCommit(bookcommit);
        if (flag > 0) {
            return BaseJSONResult.ok();
        } else {
            return BaseJSONResult.errorMsg(C.errmsg.insertError);
        }
    }

    /**
     * 获取二手书下评论
     */
    @RequestMapping(path = "/getCommitByBookid/{bookid}", method = RequestMethod.GET)
    public BaseJSONResult getCommitByBookid(@PathVariable("bookid") String bookid) {
        if (bookid == null || bookid.equals("")) {
            return BaseJSONResult.errorMsg("参数错误");
        }
        List<Bookcommit> commits = mBookSercondService.getAllCommit(bookid);
        return BaseJSONResult.ok(commits);
    }

    /**
     * 删除二手书下评论
     */
    @RequestMapping(path = "/deleteBookSecond/{commitid}", method = RequestMethod.DELETE)
    public BaseJSONResult deleteBookSecond(@PathVariable("commitid") Long commitid) {
        int flag = mBookSercondService.deleteCommit(commitid);
        if (flag > 0) {
            return BaseJSONResult.ok();
        }else{
            return BaseJSONResult.errorMsg(C.errmsg.deleteError);
        }
    }
}
